import os
from PIL import Image
from concurrent.futures import ThreadPoolExecutor, as_completed

def jpg_to_png(jpg_file_path, png_file_path):
    try:
        with Image.open(jpg_file_path) as img:
            # 确保图像以RGB模式打开，避免Alpha通道问题
            if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info):
                img = img.convert('RGB')
            img.save(png_file_path, 'PNG')
            print(f"Converted: {jpg_file_path} -> {png_file_path}")
            return True
    except Exception as e:
        print(f"Error converting {jpg_file_path}: {e}")
        return False

def convert_all_jpgs_in_tree(root_directory, max_workers=4):
    futures = []
    converted_files = []

    def find_jpg_files(directory):
        for dirpath, _, filenames in os.walk(directory):
            for filename in filenames:
                if filename.lower().endswith('.jpg'):
                    yield os.path.join(dirpath, filename)

    # 创建线程池并提交任务
    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        for jpg_file in find_jpg_files(root_directory):
            png_file = os.path.splitext(jpg_file)[0] + '.png'
            future = executor.submit(jpg_to_png, jpg_file, png_file)
            futures.append(future)

        # 收集完成的任务
        for future in as_completed(futures):
            if future.result():
                converted_files.append(future)

    print(f"Total files converted: {len(converted_files)}")

# 使用示例
root_directory_path = 'D:\Czk_EveryNote\ImageBed-master'  # 输入你的根目录路径
convert_all_jpgs_in_tree(root_directory_path, max_workers=8)  # 可以调整max_workers参数来控制并发度